package org.panda.ibog.service;

import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import com.vladsch.flexmark.ast.Node;
import com.vladsch.flexmark.ext.gfm.strikethrough.StrikethroughExtension;
import com.vladsch.flexmark.ext.tables.TablesExtension;
import com.vladsch.flexmark.html.HtmlRenderer;
import com.vladsch.flexmark.parser.Parser;
import com.vladsch.flexmark.util.options.MutableDataSet;
import org.panda.ibog.domain.MarkdownTextBean;
import org.panda.ibog.domain.RenderedMarkdonwTextBean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URL;
import java.util.Arrays;

@Service("markdownService")
public class SimpleMarkdownService {

    public RenderedMarkdonwTextBean parse(MarkdownTextBean textBean){
        MutableDataSet options = new MutableDataSet();

        // uncomment to set optional extensions
        options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create()));

        // uncomment to convert soft-breaks to hard breaks
        //options.set(HtmlRenderer.SOFT_BREAK, "<br />\n");

        Parser parser = Parser.builder(options).build();
        HtmlRenderer renderer = HtmlRenderer.builder(options).build();

        // You can re-use parser and renderer instances
        Node document = parser.parse(textBean.getText());
        String html = renderer.render(document);  // "<p>This is <em>Sparta</em></p>\n"
        System.out.println(html);
        RenderedMarkdonwTextBean renderedTextBean = new RenderedMarkdonwTextBean(html);
        return renderedTextBean;
    }

    public String parse2(String input){
        MutableDataSet options = new MutableDataSet();

        // uncomment to set optional extensions
        options.set(Parser.EXTENSIONS, Arrays.asList(TablesExtension.create(), StrikethroughExtension.create()));

        // uncomment to convert soft-breaks to hard breaks
        options.set(HtmlRenderer.SOFT_BREAK, "<br />\n");

        Parser parser = Parser.builder(options).build();
        HtmlRenderer renderer = HtmlRenderer.builder(options).build();

        // You can re-use parser and renderer instances
        input = loadData();
        Node document = parser.parse(input);
        String html = renderer.render(document);  // "<p>This is <em>Sparta</em></p>\n"
        System.out.println(html);
        return input + "\n" + html;
    }

    public String loadData(){
        URL url = Resources.getResource("README.md");
        String res = "";
        try {
            res = Resources.toString(url, Charsets.UTF_8);
            System.out.println(res);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return res;
    }
}
